package com.chen.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.chen.entity.MemberReceiveAddress;
import com.chen.entity.OrderItem;
import com.chen.entity.OrderReturnApply;
import com.chen.entity.User;
import com.chen.mapper.MemberReceiveAddressMapper;
import com.chen.mapper.OrderItemMapper;
import com.chen.mapper.OrderMapper;
import com.chen.mapper.OrderReturnApplyMapper;
import com.chen.service.MemberReceiveAddressService;
import com.chen.service.OrderReturnApplyService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chen.utils.UserThreadLocal;
import com.chen.vo.Result;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;

/**
 * <p>
 * 订单退货申请 服务实现类
 * </p>
 *
 * @author cws
 * @since 2024-11-30
 */
@Service
public class OrderReturnApplyServiceImpl extends ServiceImpl<OrderReturnApplyMapper, OrderReturnApply> implements OrderReturnApplyService {

    @Resource
    private OrderReturnApplyMapper orderReturnApplyMapper;
    @Resource
    private MemberReceiveAddressService memberReceiveAddressService;
    @Resource
    private OrderMapper orderMapper;
    @Resource
    private OrderItemMapper orderItemMapper;

    @Override
    public Result addOrderReturnApply(OrderReturnApply orderReturnApply) {
        User user = UserThreadLocal.get();
        orderReturnApply.setUserUsername(user.getUsername());
        orderReturnApply.setReturnName(user.getNickname());
        orderReturnApply.setReturnPhone(user.getPhone());
        orderReturnApply.setStatus(0);
        MemberReceiveAddress one = memberReceiveAddressService.getOne(new LambdaQueryWrapper<MemberReceiveAddress>().eq(MemberReceiveAddress::getUserId,
                user.getId()).eq(MemberReceiveAddress::getDefaultStatus, 1));
        orderReturnApply.setCompanyAddressId(one.getId());
        orderReturnApply.setCreateTime(LocalDateTime.now());
        BigDecimal multiply = orderReturnApply.getProductRealPrice().multiply(BigDecimal.valueOf(orderReturnApply.getProductCount()));
        orderReturnApply.setReturnAmount(multiply);
        int insert = orderReturnApplyMapper.insert(orderReturnApply);
        return insert == 1 ? Result.success("添加退货申请成功") : Result.fail();
    }

    @Override
    public Result getOrderReturnApply(Long orderId, Long productId) {
        LambdaQueryWrapper<OrderReturnApply> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrderReturnApply::getOrderId, orderId);
        wrapper.eq(OrderReturnApply::getProductId, productId);
        OrderReturnApply one = orderReturnApplyMapper.selectOne(wrapper);
        return Result.success(one);
    }

    @Override
    public Result updateOrderReturnApply(OrderReturnApply orderReturnApply) {
        int update = orderReturnApplyMapper.updateById(orderReturnApply);
        return update == 1 ? Result.success("修改退货申请成功") : Result.fail();
    }
}
